package org.third.integration.auth.jaas.advance.resource;

import java.security.AccessController;
import java.security.Permission;
import java.security.Principal;
import java.util.Iterator;

import javax.security.auth.Subject;

public class UserProfile implements Resource {

    private String userName;
    private String owner = "jane";

    public UserProfile() {
        Permission permission = new org.third.integration.auth.jaas.advance.resource.ResourcePermission(
                "org.third.auth.jaas.advance.example.UserProfile", "create");
        AccessController.checkPermission(permission);
    }

    public void setUserName(String userName) {
        Permission permission = new org.third.integration.auth.jaas.advance.resource.ResourcePermission(
                "org.third.auth.jaas.advance.example.UserProfile", "write", this);
        AccessController.checkPermission(permission);

        this.userName = userName;
    }

    public String getUserName() {
        Permission permission = new org.third.integration.auth.jaas.advance.resource.ResourcePermission(
                "org.third.auth.jaas.advance.example.UserProfile", "read", this);
        AccessController.checkPermission(permission);

        return userName;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String newOwner) {
        Permission permission = new org.third.integration.auth.jaas.advance.resource.ResourcePermission(
                "org.third.auth.jaas.advance.example.UserProfile", "write", this);
        AccessController.checkPermission(permission);

        this.owner = newOwner;
    }

    public boolean fulfills(Subject subject, String relationShip) {

        if ("janesManager".equalsIgnoreCase(relationShip) && getOwner().equals("jane")) {
            Iterator principalIterator = subject.getPrincipals().iterator();
            while (principalIterator.hasNext()) {
                Principal principal = (Principal) principalIterator.next();
                if (principal.getName().equals("lou"))
                    return true;
            }
        }

        return false;
    }

}
